var utils = require('../../utils/util.js')
const Monitor = require('../../utils/monitor.js').Monitor

Page(Monitor.hookApp({
  data: {
    region: ['北京', '北京'],
    imgUrl: getApp().globalData.imgUrl,
    inputVal: '',
    forList: [],
    showOpen: true,
    str:'',
    fromOrder:false,
    nowPosition: '' //现在所在区域的省市区
  },


  chooseMap() { //点击查看地图
    wx.navigateTo({
      url: '/elsePage/pages/map/map',
    })
  },
  getFirstDay(compont, emptyArr, startIdx) {
    for (let prop in compont) {
      if (compont[prop] == emptyArr[startIdx]) {
        return prop
      }
    }
  },
  reduce(arr) {
    let len = arr.length,
      obj = {},
      retArr = []
    for (let i = 0; i < len; i++) {
      obj[arr[i]] = 1
    }
    for (let prop in obj) {
      retArr.push(prop)
    }
    return retArr
  },
  explane() {
    let forList = this.data.forList
    let compont = {
      '1': '周一',
      '2': '周二',
      '3': '周三',
      '4': '周四',
      '5': '周五',
      '6': '周六',
      '7': '周日'
    }
    forList.map((value) => {
      let arr = value.openWeek
      emptyArr = [] //   数据转换成的 日期数组
      arr.forEach((val) => {
        emptyArr.push(compont[val])
      })
      let len = emptyArr.length,
        startNum = 0, // 出现不同的日子时的索引
        numArr = [],
        num = this.getFirstDay(compont, emptyArr, 0); // 起始是周几
      for (let i = 0; i < len; i++) {
        if (compont[num] != emptyArr[i]) {
          num = this.getFirstDay(compont, emptyArr, startNum)
          numArr.push(startNum)
        }
        startNum++
        num++
      }
      let numArrLen = numArr.length,
        finallArr = []; //最终结果
      for (let i = -1; i < numArrLen; i++) {
        finallArr.push(emptyArr.slice(numArr[i], numArr[i + 1])) // 截取数组 push进去最终的数组
      }
      let showArr = []
      finallArr.forEach((val) => {
        let str = '',
          arr = this.reduce(val);
        if (val.length > 2) {
          str = `${arr[0]}至${arr[arr.length - 1]}`
        } else if (val.length == 1) {
          str = `${arr[0]}`
        } else {
          str = `${arr[0]} ${arr[1]}`
        }
        showArr.push(str)
      })
      value.dateArr = showArr
    })
    this.setData({
      forList: forList
    })
  },


  back(e) { // 点击跳回上一页
    let pages = getCurrentPages(),
      prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    prevPage.setData({
      mydata: {
        ztdList: e.currentTarget.dataset.ztdlist
      }
    })
    wx.navigateBack({ //返回
      delta: 1
    })
  },
  goMap(e){
    console.log(e)
    let { latitude, longitude , name } = e.currentTarget.dataset.ztdlist
    wx.navigateTo({
      url: `/elsePage/pages/map/map?latitude=${latitude}&longitude=${longitude}&name=${name}`,
    })
  },





  getInputVal(e) { // 获取搜索内容
    let inputVal = e.detail.value
    this.getPointList(inputVal, this.data.nowPosition)
  },





  reSet() { // 重新选择
    this.setData({
      inputVal: '',
      nowPosition: ''
    })
    this.getPointList()
  },






  bindRegionChange(e) { // picker  选择地址
    let position = e.detail.value,
      str = ''
    position.forEach((val) => {
      str += val
    })
    this.setData({
      inputVal: '',
      nowPosition: str
    })
    this.getPointList('', str)
  },





  call(e) { // 点击拨打电话
    let tel = e.currentTarget.dataset.tel
    wx.makePhoneCall({
      phoneNumber: tel
    })
  },




  getPointList(inputVal, address) {
    wx.showLoading({
      title: '加载中...',
    })
    // inputVal --> 输入框内容， address  --> picker选择内容的字符串
    utils.API('spwx/v1.Shop/point_list', {
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      name: inputVal ? inputVal : "",
      address: address ? address : ""
    }).then(({
      data
    }) => {
      wx.hideLoading()
      if (data.positions){
        let { township  } = data.positions
        if (data.position){
          data.position.splice(0,1)
          let str = data.position.join('') + township
          this.setData({
            str
          })
        }
        
      }
      this.setData({
        region: data.position,
        forList: data.list ? data.list : [], // 自提点信息
      })
      this.explane()
    })
  },
  getPosition() { //获取地址
    let that = this
    wx.getLocation({ //获取地址      经纬度
      type: 'wgs84',
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude
        })
        that.getPointList(that.data.inputVal)
        that.setData({
          showOpen: true
        })
      },
      fail() {
        that.setData({
          showOpen: false
        })
      }
    })
  },
  onLoad(o) {
    this.setData({
      fromOrder : false
    })
  },
  onShow() {
    this.getPosition()
  }

}))